package org.hako.recite.word.test;

import java.io.InputStream;
import java.util.List;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordListParseException;
import org.hako.recite.word.parser.factory.WordListParserFactory;
import org.hako.recite.word.parser.impl.UnsupportedFileExtensionException;
import org.hako.recite.word.test.impl.ConsoleWordTest;
import org.hako.recite.word.test.impl.gui.swing.SwingWordTest;
import org.hako.recite.word.test.impl.gui.swt.SWTWordTest;
import org.hako.recite.word.words.WordSet;
import org.hako.recite.word.words.impl.DefaultWordSet;
import org.hako.recite.word.words.impl.IndexHandlerFactory;

/**
 * Factory of {@link WordTest}.
 * 
 * @author xnnyygn
 */
public class WordTestFactory {

	private WordListParserFactory parserFactory;

	/**
	 * Create
	 */
	public WordTestFactory() {
		super();
		parserFactory = new WordListParserFactory();
	}

	/**
	 * Create
	 * 
	 * @param filePath
	 * @param profile
	 * @param displayMode
	 * @return
	 * @throws WordListParseException
	 * @throws UnsupportedFileExtensionException
	 */
	public WordTest create(String filePath, WordTestProfile profile,
			WordTestDisplayMode displayMode) throws WordListParseException,
			UnsupportedFileExtensionException {
		return create(parserFactory.getParser(filePath).parse(filePath)
				.getWords(), profile, displayMode);
	}

	/**
	 * Create
	 * 
	 * @param stream
	 * @param profile
	 * @param displayMode
	 * @return
	 * @throws WordListParseException
	 */
	public WordTest create(InputStream stream, WordTestProfile profile,
			WordTestDisplayMode displayMode) throws WordListParseException {
		return create(parserFactory.getParser().parse(stream).getWords(),
				profile, displayMode);
	}

	/**
	 * Create
	 * 
	 * @param wordList
	 * @param profile
	 * @param displayMode
	 * @return
	 */
	public WordTest create(List<Word> wordList, WordTestProfile profile,
			WordTestDisplayMode displayMode) {
		if (isWindows() || WordTestDisplayMode.SWT.equals(displayMode)) {
			return new SWTWordTest(wordList, profile);
		} else if (WordTestDisplayMode.SWING.equals(displayMode)) {
			return new SwingWordTest(wordList, profile);
		}

		// default is console
		IndexHandlerFactory indexHandlerFactory = new IndexHandlerFactory();
		WordSet words = new DefaultWordSet(wordList,
				indexHandlerFactory.create(wordList.size(), profile));
		return new ConsoleWordTest(new WordTestResource(words, profile));
	}

	/**
	 * Check if operation system of client is windows.
	 * 
	 * @return
	 */
	private boolean isWindows() {
		String os = System.getProperty("os.name").toLowerCase();
		return os.indexOf("win") >= 0;
	}

}
